<template>
  <div class="videocontainer">
    <img src="../assets/login/xct_bg.jpg" style="width: 100%;height: 100%" >
    <el-form class="loginForm"
      :model="loginForm" :rules="loginRules" ref="loginRef" v-if="isShowQRCode">
      <div class="title">生态环境实验室信息管理系统</div>
      <div class="card">
        <div style="height: 1.94444vh">
          <span class="userName">机构</span>
        </div>
        <div>
          <el-form-item style="margin-top: 1.111vh; margin-bottom: 4.3518vh !important" prop="orgId">
            <el-select style="width: 100%;" placeholder="请输入机构关键字" clearable filterable remote reserve-keyword
              v-model="loginForm.orgId" remote-show-suffix :remote-method="remoteMethod" :loading="loading1"
              @change="isOrgId">
              <el-option v-for="item in orgList" :key="item.orgId" :value="item.orgId" :label="item.orgName" />
            </el-select>
          </el-form-item>
        </div>
        <div style="height: 1.94444vh">
          <span class="userName">用户名</span>
        </div>
        <el-form-item prop="username" class="login-form-item"
          style="margin-top: 1.111vh; margin-bottom: 4.3518vh !important">
          <input placeholder="请输入用户名" type="text" :class="redValid1" :maxlength="20" v-model="loginForm.username"
            @change="isUserName" />
        </el-form-item>

        <div style="height: 1.944vh">
          <span class="userName">密码</span>
        </div>
        <el-form-item prop="password" class="login-form-item" style="margin-top: 1.111vh; margin-bottom: 4vh !important">
          <input class="password" placeholder="请输入密码" v-model="loginForm.password" :class="redValid2" :maxlength="16"
            @keyup.enter="handleLogin" :type="type" @change="isPassword" />
          <img :src="passwordImgUrl" class="passwordImg" @click="passwordImgClick" />
          <!-- <img src="../assets/login/empty.png" @click="emptyClick" class="emptyImg" v-if="loginForm.password"> -->
        </el-form-item>
        <div v-if="captchaEnabled">
          <div style="height: 1.944vh">
            <span class="userName">验证码</span>
          </div>
          <el-form-item prop="code" style="margin-top: 1.111vh; margin-bottom: 2.9629vh !important; height: 6.66666vh"
            class="login-form-item">
            <el-row>
              <el-col :span="15">
                <input v-model="loginForm.code" placeholder="请输入验证码" @change="isCoed" :class="redValid3"
                  @keyup.enter="handleLogin" style="width:90%" />
              </el-col>
              <el-col :span="9">
                <img :src="codeUrl" @click="getCode" style="height: 6.66666vh; width: 7.8125vw" />
              </el-col>
            </el-row>
          </el-form-item>
        </div>
        <div style="text-align: right; margin-right: 0.260vw;" class="checkBoxDiv">
          <el-checkbox style="margin-bottom: 2.77777vh !important;" size="large" v-model="loginForm.rememberMe">
            <span style="font-size: 1.093vw; font-family: Inter-Regular, Inter; line-height: 15px">记住密码</span>
          </el-checkbox>
            <div class="app-download-text" @click="changeForm(false)" 
            >APP下载</div>
        </div>
        <el-form-item style="width: 100%">
          <el-button :loading="loading" size="large" type="success"
            style="width: 100%; height: 6.6666vh ; font-size:1.093vw;background-color: #0099FF !important;"
            @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-form class="loginForm"
              v-else>
        <transition name="el-zoom-in-bottom">
            <div class="card qr-code-div" v-show="!isShowQRCode">
                <div class="qr-title">APP下载</div>
                <img class="qr-image"
                        :src="baseURL+'/system/app/version/qr'"
                        fit="fit"/>
                <div>请使用浏览器扫描二维码进行下载！</div>
                <el-button class="qr-btn" plain @click="changeForm(true)">返回</el-button>
            </div>
        </transition>
    </el-form>

  </div>
</template>

<script setup>
import {getCodeImg, getOrgList, getQRImg} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import eyeOffImage from "@/assets/login/EyeOff.png";
import eyeImage from "@/assets/login/Eye.png";
import axios from "axios";
import {getToken} from "@/utils/auth";
import {blobValidate} from "@/utils/ruoyi";
const baseURL = import.meta.env.VITE_APP_BASE_API;

const userStore = useUserStore();
const router = useRouter();
const { proxy } = getCurrentInstance();
const redValid1 = ref("redValid1");
const redValid2 = ref("redValid1");
const redValid3 = ref("redValid1");
const redValid4 = ref("redValid1");
const orgList = ref([])
const loading1 = ref(false)
const isShowQRCode = ref(true)
const qrurl = ref("")

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  orgId: "",
  orgName: "",
  code: "",
  uuid: "",

});

const type = ref("password");

const loginRules = {
  orgId: [{ required: true, trigger: "blur", message: "请输入您的机构" }],
  username: [{ required: true, trigger: "blur", message: "请输入您的用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");

const passwordImgUrl = ref(eyeOffImage);

const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

function handleLogin() {
  redValid1.value = "redValid1";
  redValid2.value = "redValid1";
  redValid3.value = "redValid1";
  redValid4.value = "redValid1";
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then(() => {
          router.push({ path: redirect.value || "/" });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    } else {
      if (loginForm.value.username == "") redValid1.value = "redValid";
      if (loginForm.value.password == "") redValid2.value = "redValid";
      if (loginForm.value.code == "") redValid3.value = "redValid";
      if (loginForm.value.orgId == "") redValid4.value = "redValid";
    }
  });
}

function isOrgId(val) {
  proxy.$refs.loginRef.validateField(["orgId"], valid => {
    if (valid) {
      redValid4.value = "redVali1";
      loginForm.value.orgName = proxy.getItemByArray(
        orgListOld.value,
        "orgId",
        val,
        "orgName"
      )
      Cookies.set("orgId", loginForm.value.orgId, { expires: 30 });
      Cookies.set("orgName", loginForm.value.orgName, { expires: 30 });
    } else {
      if (loginForm.value.orgId == "") redValid4.value = "redValid";
    }
  });
}

function isPassword() {
  proxy.$refs.loginRef.validateField(["password"], valid => {
    if (valid) {
      redValid2.value = "redVali1";
    } else {
      if (loginForm.value.password == "") redValid2.value = "redValid";
    }
  });
}

function isCoed() {
  proxy.$refs.loginRef.validateField(["code"], valid => {
    if (valid) {
      redValid3.value = "redVali1";
    } else {
      if (loginForm.value.code == "") redValid3.value = "redValid";
    }
  });
}

function isUserName() {
  proxy.$refs.loginRef.validateField(["username"], valid => {
    if (valid) {
      redValid1.value = "redVali1";
    } else {
      if (loginForm.value.username == "") redValid1.value = "redValid";
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}
function getQRImage() {
    getQRImg().then(res => {
        var blob = new Blob([res]);
        // 创建一个URL指向这个Blob对象
        var imageUrl = URL.createObjectURL(blob);
        console.log('55555',imageUrl)
        qrurl.value = imageUrl;
  });
}
// getQRImage();

function getCookie() {
  const username = Cookies.get("username");
  const orgId = Cookies.get("orgId");
  const orgName = Cookies.get("orgName");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    orgId: orgId === undefined ? loginForm.value.orgId : orgId,
    orgName: orgName === undefined ? loginForm.value.orgName : orgName,
  };
  if (orgId === undefined) {
    orgList.value = []
  } else {
    orgList.value = [{ orgId, orgName }]
  }
}

function passwordImgClick() {
  if (passwordImgUrl.value == eyeImage) {
    passwordImgUrl.value = eyeOffImage;
    type.value = "password";
  } else {
    passwordImgUrl.value = eyeImage;
    type.value = "text";
  }
}

// function emptyClick() {
//   loginForm.value.password = ""
// }

nextTick(() => {
  if (captchaEnabled.value) {
    getCode();
  }
})

const orgListOld = ref([])

function remoteMethod(val) {
  if (val) {
    loading1.value = true;
    setTimeout(() => {
      getOrgList({ keyWord: val }).then((res) => {
        loading1.value = false;
        orgList.value = JSON.parse(JSON.stringify(res.rows))
        orgListOld.value = JSON.parse(JSON.stringify(res.rows))
      });
    }, 200);
  } else {
    orgList.value = [];
  }
}

getCookie();
function changeForm(val) {
    isShowQRCode.value = val;
}
</script>

<style scoped>
:deep(.el-input__wrapper) {
  background-color: #f2f2f2;
  border-radius: 0.625vw;
  box-shadow: none !important;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f67373 inset !important;
}

:deep(.el-input__inner) {
  font-size: 1.093vw;
  padding-left: 0.375vw;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: none !important;
}

:deep(.el-input) {
  height: 6.6666vh;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f67373 inset !important;
}
</style>

<style>

.videocontainer {
  position: fixed;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.title {
  width: 27vw;
  height: 3.335999vh;
  font-size: 1.5625vw;
  font-family: Inter-Medium, Inter;
  font-weight: 500;
  color: #ffffff;
  line-height: 3.2407vh;
  margin: 0 auto;
  text-align: center;
}

.loginForm {
  width: 26.563vw;
  position: absolute;
  top: 50%;

  right: 9.21875vw;
  transform: translate(0, -50%);
}

.qr-code-div{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;

    .qr-title{
        color: #484848;
        font-size: 1.593vw;
        height: 1.944vh !important;
        line-height: 1.944vh;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
    }
    .qr-image{
        width: 20.5625vw;
        /*height: 0;*/
        margin: 1vh 0 0.5vh 0;
    }
    .qr-btn{
        margin-top: 2vh;
        width: 100%; height: 6.6666vh ; font-size:1.093vw;
        border: 1px solid #d9d9d9 !important;
        box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
        color: rgba(0, 0, 0, 0.88);
        height: 4vh;

    }

}

.card {
  margin-top: 1.851vh;
  width: 26.5625vw;
  background: #ffffff;
  border-radius: 0.781vw;
  opacity: 1;
  padding: 7.6851vh 2.343vw 6.388vh;
}

.userName {
  color: #484848;
  font-size: 1.093vw;
  height: 1.944vh !important;
  line-height: 1.944vh;
}

.login-form-item input::-webkit-input-placeholder {
  /*WebKit browsers*/

  color: #cacaca;
}

.login-form-item input {
  width: 21.875vw;
  height: 6.66666vh;
  border-radius: 0.625vw;
  box-sizing: border-box;
  border: 0vw;
  background-color: #f2f2f2;
  font-size: 1.093vw;
  color: #000;
  outline: none;
  padding-left: 0.9375vw;
}

.checkBoxDiv{
    display: flex;
    justify-content: space-between;
    /*align-items: center;*/

    .app-download-text{
        font-size: 0.88vw;
        /*font-family: Inter-Regular, Inter;*/
        cursor: pointer;
        color: rgb(0, 164, 253);
        height: 40px;
        line-height: 40px;

        color: #0099FF !important;
    }
}
/**.el-checkbox__inner {}*/

.checkBoxDiv .el-checkbox__inner::after {}

.passwordImg {
  position: absolute;
  right: 0.9375vw;
  width: 1.875vw;
  height: 1.875vw;
}

/* .emptyImg {
  position: absolute;
  width: 1.5vw;
  height: 1.5vw;
  right: 3.3vw;
} */

.loginForm .el-form-item__error {
  color: var(--el-color-danger);
  font-size: 0.9375vw;
  line-height: 1;
  margin-top: 0.8823vh;
  position: absolute;
  top: 93%;
  padding: 0;
  left: 0;
}

.loginForm .el-form-item__error::before {
  content: "";
  display: inline-block;
  position: relative;
  top: 0.3921vh;
  width: 1.07375vw;
  height: 1.07375vw;
  background-image: url("../assets/login/提示.png");
  background-size: cover;
  margin-right: 2px;
}

.redValid {
  border: 1px #f67373 solid !important;
}

.redValid1 {
  border: 0px !important;
}
</style>
